﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace wsy.ext.Devlib.ExtensionMethods
{
    public static class JavaExt
    {
        public static Dictionary<string, string> LoadJavaPropertiesFromFile(this string file)
        {
            return LoadJavaPropertiesFromDynamic(File.ReadAllLines(file));
        }

        public static Dictionary<string, string> LoadJavaPropertiesFromStream(this Stream file)
        {
            List<string> lines = new List<string>();
            file.Position = 0;
            using (StreamReader sr = new StreamReader(file))
            {
                while (!sr.EndOfStream)
                {
                    lines.Add(sr.ReadLine());
                }
            }
            return LoadJavaPropertiesFromDynamic(lines);

        }

        private static Dictionary<string, string> LoadJavaPropertiesFromDynamic(dynamic lines)
        {
            Dictionary<string, string> pros = new Dictionary<string, string>();
            foreach (string line in lines)
            {
                if ((!string.IsNullOrEmpty(line)) &&
                    (!line.StartsWith(";")) &&
                    (!line.StartsWith("#")) &&
                    (!line.StartsWith("'")) &&
                    (line.Contains('=')))
                {
                    int index = line.IndexOf('=');
                    string key = line.Substring(0, index).Trim();
                    string value = line.Substring(index + 1).Trim();

                    if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
                        (value.StartsWith("'") && value.EndsWith("'")))
                    {
                        value = value.Substring(1, value.Length - 2);
                    }

                    try
                    {
                        //ignore dublicates
                        pros.Add(key, value);
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }
            return pros;
        }

    }
}
